/**
 * Copyright (c) 2002-2011 旭鸣信息
 * All rights reserved. 
 * File：GoodsGroupDaoImpl.java
 * History:
 *       May 11, 2012: Initially created, liuzhi.
 */
package com.xteam.ecsystem.dao.Impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xteam.ecsystem.base.SystemContent;
import com.xteam.ecsystem.dao.IGoodsGroupDao;
import com.xteam.ecsystem.entities.BaseGoodsAttribute;
import com.xteam.ecsystem.entities.BaseGoodsGroup;
import com.xteam.ecsystem.entities.BaseGoodsInfo;
import com.xteam.ecsystem.entities.BaseGoodsType;
import com.xteam.ecsystem.entities.BaseGroupAttribute;
import com.xteam.ecsystem.entities.BaseTypeAttribute;
import com.xteam.ecsystem.utils.PageCenterStation;

/**
 * 商品分类数据访问实现类
 * 
 * @author liuzhi
 * 
 */
@Repository
public class GoodsGroupDaoImpl extends DDLPrefix implements IGoodsGroupDao {

	@SuppressWarnings("unchecked")
	@Autowired
	private BaseDaoImpl baseDao;

	/**
	 * @see com.xteam.ecsystem.dao.IGoodsGroupDao#delObject(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public void delObject(String id) {
		List list = new ArrayList();
		String hql = "";
		
		try {
			hql = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE + "bggParent = ?";
			list = this.baseDao.find(hql, new Object[]{id});
			
			if (list != null && !list.isEmpty()) {
				for (int i = 0; i < list.size(); i++) {
					BaseGoodsGroup bgg = (BaseGoodsGroup)list.get(i);
					delObject(bgg.getBggId());
				}
			}
			
			// 1、先删除商品分类属性列表
			hql = SQL_DELETE + SQL_FROM + BaseGroupAttribute.REF + SQL_WHERE + "bgaGgroup = ?";
			this.baseDao.executeUpdate(hql, new Object[]{id});
			
			// 2、再删除商品分类
			hql = SQL_DELETE + SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE + "bggId = ?";
			this.baseDao.executeUpdate(hql, new Object[]{id});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public String getGoodsGroupList(int pageIndex, int pageSize, String bggName) {
		JSONObject jo = new JSONObject();
		try {
			List list = new ArrayList();

			String hql = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE + " 1=1 ";
			String countHQL = SQL_SELECT + " count(*) " + SQL_FROM
					+ BaseGoodsGroup.REF + SQL_WHERE + " 1=1 ";

			if (bggName != null && bggName.length() > 0
					&& !bggName.equals("undefined")
					&& !bggName.equals("null")) {
				hql += SQL_AND + " bggName " + SQL_LIKE + " ? ";
				countHQL += SQL_AND + " bggName " + SQL_LIKE + " ? ";
				list.add("%" + bggName + "%");

			}

			PageCenterStation<?> p = (PageCenterStation<?>) this.baseDao.queryList(countHQL, hql, list
					.toArray(), pageIndex * pageSize, pageSize);
			
			jo = JSONObject.fromObject(p);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return jo.toString();
	}

	/**
	 * @see com.xteam.ecsystem.dao.IGoodsGroupDao#saveOrUpdateObject(java.lang.Object,
	 *      java.lang.String)
	 */
	public String saveOrUpdateObject(Object obj, String id) {
		try {
			if (id != null && !id.equals("") && id.length() > 0) {
				this.baseDao.update(obj);
				return id;
			} else {
				BaseGoodsGroup goodsGroup = (BaseGoodsGroup) obj;
				this.baseDao.save(goodsGroup);
				return goodsGroup.getBggId();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@SuppressWarnings("unchecked")
	public String getGoodsGroupInfoById(String id) {
		JSONObject jo = new JSONObject();
		try {
			List list = new ArrayList();

			String hql = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE + " 1=1 "
					+ SQL_AND + " bggId=?";
			list = this.baseDao.find(hql, new Object[] { id });
			
			if(list != null && list.size() > 0){
				jo = JSONObject.fromObject((BaseGoodsGroup) list.get(0));
				return jo.toString();
			}
			

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

	@SuppressWarnings("unchecked")
	public void updateBggStateById(String id) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseGoodsGroup");

			BaseGoodsGroup goodsGroup = (BaseGoodsGroup) this.baseDao.get(
					clazz, id);
			if (goodsGroup.getBggState() == 1) {
				goodsGroup.setBggState(0);
			} else {
				goodsGroup.setBggState(1);
			}

			this.baseDao.saveOrUpdate(goodsGroup);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public void updateBggBestById(String id) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseGoodsGroup");

			BaseGoodsGroup goodsGroup = (BaseGoodsGroup) this.baseDao.get(
					clazz, id);
			if (goodsGroup.getBggBest() == 1) {
				goodsGroup.setBggBest(0);
			} else {
				goodsGroup.setBggBest(1);
			}

			this.baseDao.saveOrUpdate(goodsGroup);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public void updateBggNewById(String id) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseGoodsGroup");

			BaseGoodsGroup goodsGroup = (BaseGoodsGroup) this.baseDao.get(
					clazz, id);
			if (goodsGroup.getBggNew() == 1) {
				goodsGroup.setBggNew(0);
			} else {
				goodsGroup.setBggNew(1);
			}

			this.baseDao.saveOrUpdate(goodsGroup);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public void updateBggHotById(String id) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseGoodsGroup");

			BaseGoodsGroup goodsGroup = (BaseGoodsGroup) this.baseDao.get(
					clazz, id);
			if (goodsGroup.getBggHot() == 1) {
				goodsGroup.setBggHot(0);
			} else {
				goodsGroup.setBggHot(1);
			}

			this.baseDao.saveOrUpdate(goodsGroup);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void updateBggBuyById(String id) {
		Class clazz = null;
		try {
			clazz = Class.forName("com.xteam.ecsystem.entities.BaseGoodsGroup");

			BaseGoodsGroup goodsGroup = (BaseGoodsGroup) this.baseDao.get(
					clazz, id);
			if (goodsGroup.getBggBuy() == 1) {
				goodsGroup.setBggBuy(0);
			} else {
				goodsGroup.setBggBuy(1);
			}

			this.baseDao.saveOrUpdate(goodsGroup);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public JSONArray getGoodsGroupJsonArray(BaseGoodsGroup goodsGroup,
			String bggParent) {
		JSONArray jarray = new JSONArray();

		if (goodsGroup != null) {
			JSONObject obj = new JSONObject();

			obj.put("bggId", goodsGroup.getBggId());
			obj.put("bggParent", goodsGroup.getBggParent());
			obj.put("bggName", goodsGroup.getBggName());
			obj.put("bggUnits", goodsGroup.getBggUnits());
			obj.put("bggOrder", goodsGroup.getBggOrder());
			obj.put("bggBuy", goodsGroup.getBggBuy());
			obj.put("bggBest", goodsGroup.getBggBest());
			obj.put("bggNew", goodsGroup.getBggNew());
			obj.put("bggHot", goodsGroup.getBggHot());
			obj.put("bggSection", goodsGroup.getBggSection());
			obj.put("bggState", goodsGroup.getBggState());			
			obj.put("expanded", false);

			String hql_r = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE
					+ " bggParent =?";
			List list_r = this.baseDao.find(hql_r, new Object[] { bggParent });
			if (list_r.size() > 0) {
				JSONObject obj_r = new JSONObject();

				for (int i = 0; i < list_r.size(); i++) {
					BaseGoodsGroup group = (BaseGoodsGroup) list_r.get(i);

					JSONArray jarray_r = getGoodsGroupJsonArray(group, group
							.getBggId());

					obj_r.accumulate("temp2", jarray_r);
					if (obj_r.get("temp2") instanceof JSONArray) {
						int size = obj_r.getJSONArray("temp2").size();
						for (int j = 0; j < size; j++) {
							if (obj_r.getJSONArray("temp2").get(j) instanceof JSONArray) {
								JSONObject obj3 = obj_r.getJSONArray("temp2")
										.getJSONArray(j).getJSONObject(0);
								obj_r.getJSONArray("temp2").remove(j);
								obj_r.getJSONArray("temp2").add(j, obj3);
							}
						}
					}

					obj.put("children", obj_r.get("temp2"));
				}
			}

			jarray.add(obj);

		} else {
			List bggIdList = new ArrayList();
			String hql = SQL_SELECT + " bggId " + SQL_FROM + BaseGoodsGroup.REF
					+ SQL_GROUPBY + " bggId " + SQL_ORDERBY + " bggId asc ";

			bggIdList = this.baseDao.find(hql);

			for (int i = 0; i < bggIdList.size(); i++) {
				String bggId = (String) bggIdList.get(i);

				String hql_1 = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE
						+ " bggId=? " + SQL_AND + " bggParent='0' "; //之前为0
				// 查询所有父节点为0的商品分类信息
				List gginfoList = this.baseDao.find(hql_1,
						new Object[] { bggId });

				JSONObject ggObj[] = new JSONObject[gginfoList.size()];
				for (int j = 0; j < gginfoList.size(); j++) {
					ggObj[j] = new JSONObject();

					BaseGoodsGroup ggInfo = (BaseGoodsGroup) gginfoList.get(j);
					ggObj[j].put("bggId", ggInfo.getBggId());
					ggObj[j].put("bggParent", ggInfo.getBggParent());
					ggObj[j].put("bggName", ggInfo.getBggName());
					ggObj[j].put("bggUnits", ggInfo.getBggUnits());
					ggObj[j].put("bggOrder", ggInfo.getBggOrder());
					ggObj[j].put("bggBuy", ggInfo.getBggBuy());
					ggObj[j].put("bggBest", ggInfo.getBggBest());
					ggObj[j].put("bggNew", ggInfo.getBggNew());
					ggObj[j].put("bggHot", ggInfo.getBggHot());
					ggObj[j].put("bggSection", ggInfo.getBggSection());
					ggObj[j].put("bggState", ggInfo.getBggState());					
					ggObj[j].put("expanded", false);

					String hql_2 = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE
							+ " bggParent=?";
					// 查询所有次级孩子节点的商品分类信息
					List childList = this.baseDao.find(hql_2,
							new Object[] { ggInfo.getBggId() });
					if (childList != null && childList.size() > 0) {
						JSONObject childObj = new JSONObject();

						for (int h = 0; h < childList.size(); h++) {
							BaseGoodsGroup childInfo = (BaseGoodsGroup) childList
									.get(h);

							JSONArray jarray2 = getGoodsGroupJsonArray(
									childInfo, childInfo.getBggId());

							childObj.accumulate("temp", jarray2.get(0));
						}

						if (childObj.get("temp") instanceof JSONObject) {
							JSONArray jarray3 = new JSONArray();
							jarray3.add(0, childObj.get("temp"));
							ggObj[j].put("children", jarray3);
						} else {
							ggObj[j].put("children", childObj.get("temp"));
						}
					}

					jarray.element(ggObj[j]);
				}
			}

		}

		return jarray;
	}

	@SuppressWarnings("unchecked")
	public String lazyLoadGoodsGroupTree(String bggParent) {
		if (bggParent == null || "".equals(bggParent)
				|| "null".equals(bggParent) || "undefined".equals(bggParent)) {
			bggParent = "0"; //-1 
		}
		
		List bggTreeList = new ArrayList(); 
		//不能在此添加顶级节点，因为点击子节点之后会不断产生孩子节点，而此节点也会重新被加载上去
//		Map<String, Object> topNode = new HashMap<String, Object>();
//		topNode.put("bggId", "0");
//		topNode.put("bggParent", "-1");
//		topNode.put("bggName", "顶级分类");
//		bggTreeList.add(topNode);

		//获取下一级节点
		//一：使用hql语句，返回javabean对象
		String hql = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE + " bggParent=? ";
		ArrayList list = (ArrayList)this.baseDao.find(hql, new Object[]{bggParent});
		
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				BaseGoodsGroup bgg = (BaseGoodsGroup)list.get(i);
				
				map.put("bggId", bgg.getBggId());
				map.put("bggParent", bgg.getBggParent());
				map.put("bggName", bgg.getBggName());
				bggTreeList.add(map);
			}
		}
		//二：使用sql语句，直接返回map对象
//		String sql = SQL_SELECT + "*" + SQL_FROM + " base_goods_group "	+ SQL_WHERE + " bgg_parent=?";
//		ArrayList bggList = (ArrayList)this.baseDao.queryWithSQL(Map.class, sql, bggParent);
		
		// 判断节点，是否有子节点。如果有，则处理isLeaf和expanded。
		for (int i = 0, j = bggTreeList.size(); i < j; i++) {
			HashMap node = (HashMap) bggTreeList.get(i);
			String nodeId = node.get("bggId").toString();

			String hql2 = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE	+ " bggParent=? ";
			ArrayList nodeList = (ArrayList) this.baseDao.find(hql2, new Object[] { nodeId });

			if (nodeList != null && nodeList.size() > 0) {
				node.put("isLeaf", false);
				node.put("expanded", false);
			}
		}

		// 返回处理结果
		String bggTree = PluSoft.Utils.JSON.Encode(bggTreeList);
		return bggTree;
	}

	@SuppressWarnings("unchecked")
	public String getGoodsTypeList() {
		JSONArray jo = new JSONArray();
		List list = new ArrayList();
		String hql = "";
		try {
			hql = SQL_FROM + BaseGoodsType.REF + SQL_WHERE +" 1=1 ";
			list = this.baseDao.find(hql);
			jo = JSONArray.fromObject(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return jo.toString();
	}
	
	/**
	 * 只加载可用的属性列表
	 * @see com.xteam.ecsystem.dao.IGoodsGroupDao#getGoodsTypeAttrList(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public String getGoodsTypeAttrList(String bgtId) {
		JSONArray jo = new JSONArray();
		List list = new ArrayList();
		String hql = "";
		try {
			hql = SQL_FROM + BaseTypeAttribute.REF + SQL_WHERE + " btaState=1 ";

			if (bgtId != null && bgtId != "" && !"undefined".equals(bgtId)
					&& !"null".equals(bgtId)) {
				hql += SQL_AND + " btaGtype=? ";
				list = this.baseDao.find(hql, new Object[] { bgtId });
			}else{
				list = this.baseDao.find(hql);
			}
			jo = JSONArray.fromObject(list);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return jo.toString();
	}
	
	@SuppressWarnings("unchecked")
	public String lazyLoadGoodsGroupTreeGrid(String bggParent) {
		if (bggParent == null || "".equals(bggParent)
				|| "null".equals(bggParent) || "undefined".equals(bggParent)) {
			bggParent = "0"; //-1 
		}
		
		List bggTreeList = new ArrayList(); 

		//获取下一级节点
		//一：使用hql语句，返回javabean对象
		String hql = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE + " bggParent=? ";
		ArrayList list = (ArrayList)this.baseDao.find(hql, new Object[]{bggParent});
		
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				BaseGoodsGroup bgg = (BaseGoodsGroup)list.get(i);
				
				map.put("bggId", bgg.getBggId());
				map.put("bggParent", bgg.getBggParent());
				map.put("bggName", bgg.getBggName());
				map.put("bggUnits", bgg.getBggUnits());
				map.put("bggBuy", bgg.getBggBuy());
				map.put("bggBest", bgg.getBggBest());
				map.put("bggNew", bgg.getBggNew());
				map.put("bggHot", bgg.getBggHot());
				map.put("bggSection", bgg.getBggSection());
				map.put("bggOrder", bgg.getBggOrder());
				map.put("bggState", bgg.getBggState());
				bggTreeList.add(map);
			}
		}

		// 判断节点，是否有子节点。如果有，则处理isLeaf和expanded。
		for (int i = 0, j = bggTreeList.size(); i < j; i++) {
			HashMap node = (HashMap) bggTreeList.get(i);
			String nodeId = node.get("bggId").toString();

			String hql2 = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE	+ " bggParent=? ";
			ArrayList nodeList = (ArrayList) this.baseDao.find(hql2, new Object[] { nodeId });

			if (nodeList != null && nodeList.size() > 0) {
				node.put("isLeaf", false);
				node.put("expanded", false);
			}
		}

		// 返回处理结果
		String bggTree = PluSoft.Utils.JSON.Encode(bggTreeList);
		return bggTree;
	}
	
	/**
	 * @see com.xteam.ecsystem.dao.IGoodsGroupDao#getSystemContent(int, java.lang.String, java.lang.String, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, String>> getSystemContent(int state, String value, String text, String parent) {
		String hql = "select bggId as " + value + ", bggName as " + text + ", bggParent as " + parent + 
			" from BaseGoodsGroup where bggState = " + state;
		return this.baseDao.queryListInMap(hql);
	}
	
	/**
	 * @see com.xteam.ecsystem.dao.IGoodsGroupDao#getSystemContents(java.lang.String, int, int, int)
	 */
	@SuppressWarnings("unchecked")
	public PageCenterStation<SystemContent> getSystemContents(String name, int state, int first, int max) {
		String suffix = " from base_goods_group c left join base_goods_group p on c.bgg_parent = p.bgg_id " + 
			"where c.bgg_state = " + state;
		if (name != null && !"".equals(name)) {
			suffix += " and c.bgg_name like '%" + name + "%'";
		}
		
		String countSql = "select count(c.bgg_id)" + suffix;
		long count = this.baseDao.queryCountWithSql(countSql);
		
		List<SystemContent> list = new ArrayList<SystemContent>();
		if (count > 0) {
			String querySql = "select c.bgg_id as value, c.bgg_name as text, p.bgg_name as parent" + suffix;
			List<Object[]> data = this.baseDao.queryListWithSql(querySql);
			if (data != null) {
				for (Object[] o : data) {
					String value = (o[0] == null) ? null : o[0].toString();
					String text = (o[1] == null) ? null : o[1].toString();
					String parent = (o[2] == null) ? null : o[2].toString();
					list.add(new SystemContent(value, text, parent));
				}
			}
		}
		
		return new PageCenterStation<SystemContent>(count, list);
	}
	
	@SuppressWarnings("unchecked")
	public boolean getBgaByBgaTattris(String bgaTattris){
		boolean isUsed = false;
		
		try {
			String hql = SQL_FROM + BaseGoodsAttribute.REF + SQL_WHERE + "bgaTattri in(" + bgaTattris + ")";

			List list = this.baseDao.find(hql);
			if (list != null && !list.isEmpty()) {
				isUsed = true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return isUsed;
	}
	
	@SuppressWarnings("unchecked")
	public boolean getBgiByBgg(String bggId){
		boolean isUsed = false;
		List list = new ArrayList();
		String hql = "";
		
		try {
			hql = SQL_FROM + BaseGoodsInfo.REF + SQL_WHERE + "bgiGroup = ?";
			list = this.baseDao.find(hql, new Object[]{bggId});
			
			if(list != null && !list.isEmpty()){
				isUsed = true;
			}else{
				hql = SQL_FROM + BaseGoodsGroup.REF + SQL_WHERE + "bggParent = ?";
				list = this.baseDao.find(hql, new Object[]{bggId});
				
				if(list != null && !list.isEmpty()){
					for (int i = 0; i < list.size(); i++) {
						BaseGoodsGroup bgg = (BaseGoodsGroup)list.get(i);
						isUsed = getBgiByBgg(bgg.getBggId());
						if (isUsed) break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return isUsed;
	}
}
